<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Profile extends CI_Controller {
    function __construct() {
        date_default_timezone_set('UTC');
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('file');
        $this->load->helper('url');
        $this->load->library('upload');
        $this->load->model('get_profile_infos');
        $this->load->model('settings');
        $this->load->model('manage_login');
        $this->load->model('membership_model');
        $this->load->model('manage_mag');
        $this->load->model('share_media');
        $this->load->library('s3');
    }
    public function index() {
        $userName = $this->uri->segment(1);
        if ($this->get_profile_infos->checkIfExists($userName)) {
            if(!$this->input->cookie('LEAPSESSID', TRUE)){
                redirect("/login");
            }
            $data = $this->manage_login->manageLogin();
        
//        $videos = $this->share_media->getPopVideos();
//        $photos = $this->share_media->getPhotos();
//        $articles = $this->manage_mag->getArticles();
        $data['users'] = $this->get_profile_infos->getUsers();
        $data['videos'] = $this->share_media->getMainVideos();
        $data['articles'] = $this->manage_mag->getArticles();
        $data['media'] = array_merge($data['users'],$data['videos'],$data['articles']);

            $this->load->view('profile/profile', $data);
        }else{
            echo "Error 404";
        }
    }

    function settings() {
        ;
        $this->lang->load('main', 'english');
        $data = $this->manage_login->manageLogin();
        $this->load->view('profile/settings', $data);

        
    }

    function settings_password() {
        $data = $this->manage_login->manageLogin();
        $this->load->view('profile/settings_password',$data);
    }
    
    function sharing() {
        $data = $this->manage_login->manageLogin();
        $this->load->view('profile/sharing',$data);
    }
    
    function settings_password_errors($data) {
        $this->load->view('profile/settings_password', $data);
    }

    function settings_error($incorrect) {
        $data['incorrect'] = $incorrect;
        $this->lang->load('main', 'english');
        $this->load->view('profile/settings', $data);
    }

    function submit_settings() {

        $this->load->library('form_validation');
        // field name, error message, validation rules
        $this->form_validation->set_rules('firstname', 'Name', 'trim|required');
        $this->form_validation->set_rules('lastname', 'Last Name', 'trim|required');
        $this->form_validation->set_rules('email', 'Email Address', 'trim|required|valid_email');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');

        if ($this->form_validation->run() == FALSE) {
            $this->settings();
        } else {

            $data = array(
                'username' => $this->input->post('username'),
                'email_address' => $this->input->post('email'),
                'first_name' => $this->input->post('firstname'),
                'last_name' => $this->input->post('lastname'),
                'birthday_month' => $this->input->post('birthday_month'),
                'birthday_day' => $this->input->post('birthday_day'),
                'birthday_year' => $this->input->post('birthday_year'),
                'about' => $this->input->post('about'),
                'sex' => $this->input->post('sex'),
                'city' => $this->input->post('city'),
                'state' => $this->input->post('state'),
                'team' => $this->input->post('team'),
                'country' => $this->input->post('country'),
                'height' => $this->input->post('height'),
                'weight' => $this->input->post('weight'),
                'tracer' => $this->input->post('tracer'),
                'shoe' => $this->input->post('shoe'),
                'spot' => $this->input->post('spot'),
                'website' => $this->input->post('website'),
                'twitter' => $this->input->post('twitter'),
                'facebook' => $this->input->post('facebook'),
                'skype' => $this->input->post('skype'),
                'flickr' => $this->input->post('flickr'),
                'googleplus' => $this->input->post('googleplus'),
                
            );
            $this->load->model('settings');
            $query = $this->settings->validate_settings();
            $username = $this->get_profile_infos->getUsername($this->input->cookie('LEAPSESSID'));
            if ($query) {
                $query = $this->settings->update_settings($username, $data);
                if($query){
                    redirect('http://leapdemo.com/' . $username);
                }
                else{
                    $incorrect = "an Error occured!";
                    $this->settings_error($incorrect);
                }
            } else { // incorrect username or password
                $incorrect = "The New Entries muss Match and not be Empty";
                $this->settings_error($incorrect);
            }
        }
    }

    function password_error($incorrect) {
        $data['incorrect'] = $incorrect;
        $this->lang->load('main', 'english');
        $this->settings_password_errors($data);
    }

    function submit_password() {

        $this->load->model('settings');
        $query = $this->settings->validatePass();
        if ($query) { // if the user's credentials validated...
            $query = $this->settings->update_password($username);
            redirect('/' . $username);
        } else { // incorrect username or password
            $incorrect = "The New Entries muss Match and not be Empty";
            $this->password_error($incorrect);
        }
    }

    function _createThumbnail($fileName,$_width,$_height,$width,$marker) {
        
        $img_type = '';
        if ($_width > $_height) {
            $img_type = 'wide';
            $config['height'] = $width;
            $config['width'] = ($_width/$_height)*$width;
        } else if ($_width < $_height) {
            $img_type = 'landscape';
            $config['width'] = $width;
            $config['height'] = ($_height/$_width)*$width;
        } else {
            $img_type = 'square';
            $config['width'] = $width;
            $config['height'] = $width;
        }
        $config['image_library'] = 'gd2';
        $config['source_image'] = $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $fileName;
        $config['new_image'] = $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $fileName;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['thumb_marker'] = $marker;
        
        $this->image_lib->initialize($config);
        if (!$this->image_lib->resize()){
            return $this->image_lib->display_errors();
        }
        $fileName_c = str_replace('.',$marker.'.', $fileName);
        //crop
        $conf_new = array(
            'image_library' => 'gd2',
            'source_image' => $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $fileName_c,
            'maintain_ratio' => FALSE,
            'create_thumb' => FALSE,
            'width' => $width,
            'height' => $width
        );

        if ($img_type == 'wide') {
            $conf_new['x_axis'] = ($config['width'] - $width) / 2;
            $conf_new['y_axis'] = 0;
        } else if ($img_type == 'landscape') {
            $conf_new['x_axis'] = 0;
            $conf_new['y_axis'] = ($config['height'] - $width) / 2;
        } else {
            $conf_new['x_axis'] = 0;
            $conf_new['y_axis'] = 0;
        }
        $this->image_lib->clear();
        
        $this->image_lib->initialize($conf_new);

        if ( ! $this->image_lib->crop())
        {
            echo $this->image_lib->display_errors();
        }
        
    }
    function upload_cover() {
        $config['upload_path'] = './uploads';
        $config['allowed_types'] = 'gif|jpg|png|JPG|jpeg';
        $config['max_size'] = '100000';
        $config['max_width'] = '2624';
        $config['max_height'] = '2268';

        $this->upload->initialize($config);
        if (!$this->upload->do_upload("photoCover")) {
            $error = array('error' => $this->upload->display_errors());
            echo $error["error"];
        }
        else{
            $data = $this->upload->data();
            $big_picture = $this->s3->putObjectFile($data["file_path"].$data['file_name'], "leap_s3", $this->input->cookie('LEAPSESSID') . "/cover" . $data['file_ext'],"public-read");
            $profile_cover = "https://s3.amazonaws.com/leap_s3/".$this->input->cookie('LEAPSESSID'). "/cover" . $data['file_ext'];
            $query = $this->manage_login->updateData("profile_cover",$profile_cover,$this->input->cookie('LEAPSESSID'));
            $cover_init_pos = "0";
            $query = $this->manage_login->updateData("profile_cover_pos",$cover_init_pos,$this->input->cookie('LEAPSESSID'));
            echo "<img src='".$profile_cover."'  class='preview' height='500'>";
            $this->settings->SureRemoveDir('./uploads', false);
            $this->manage_login->updateData("profile_cover_pos","0",$this->input->cookie('LEAPSESSID'));
        }
    }
    function upload_pp() {
        $this->load->library('image_lib'); 
        $config['upload_path'] = './uploads';
        $config['allowed_types'] = 'gif|jpg|png|JPG|jpeg';
        $config['max_size'] = '100000';
        $config['max_width'] = '2624';
        $config['max_height'] = '2268';

        $this->upload->initialize($config);
        if (!$this->upload->do_upload("photoProfile")) {
            $error = array('error' => $this->upload->display_errors());
            echo $error["error"];
        }
        else{
        
            $username = $this->get_profile_infos->getUsername($this->input->cookie('LEAPSESSID'));
            $data = $this->upload->data();

            $user = $this->membership_model->getUserInfos($username);
            $org_picture = $this->s3->putObjectFile($data["file_path"] . $data["file_name"], "leap_s3", $this->input->cookie('LEAPSESSID') . "/" . $data["orig_name"], "public-read");

            $this->_createThumbnail($data["file_name"],$data["image_width"],$data["image_height"],300,"_big");
        
            echo $this->_createThumbnail($data["file_name"],$data["image_width"],$data["image_height"],50,"_thumb");
            
            $big_picture = $this->s3->putObjectFile($data["file_path"] . str_replace(".", "_big.", $data["file_name"]), "leap_s3", $user[0]["user_id"] . "/" . str_replace(".", "_big.", $data["orig_name"]), "public-read");
            $thmub_picture = $this->s3->putObjectFile($data["file_path"] . str_replace(".", "_thumb.", $data["file_name"]), "leap_s3", $user[0]["user_id"] . "/" . str_replace(".", "_thumb.", $data["orig_name"]), "public-read");

            $profile_pic = "https://s3.amazonaws.com/leap_s3/" . $user[0]["user_id"] . "/" . str_replace(".", "_big.", $data["orig_name"]);
            $profile_pic_thumb = "https://s3.amazonaws.com/leap_s3/" . $user[0]["user_id"] . "/" . str_replace(".", "_thumb.", $data["orig_name"]);
            $profile_pic_original = "https://s3.amazonaws.com/leap_s3/" . $user[0]["user_id"] . "/" . $data["orig_name"];

            $this->settings->SureRemoveDir('./uploads', false);
            echo $profile_pic."'  class='preview' height='100' width='100'>";
            $this->manage_login->updateData("profile_pic",$profile_pic,$this->input->cookie('LEAPSESSID'));
            $this->manage_login->updateData("profile_pic_thumb",$profile_pic_thumb,$this->input->cookie('LEAPSESSID'));
        }
    }
    function upload_picture() {
        $this->load->library('image_lib'); 
        $config['upload_path'] = './uploads';
        $config['allowed_types'] = 'gif|jpg|png|JPG|jpeg';
        $config['max_size'] = '100000';
        $config['max_width'] = '2624';
        $config['max_height'] = '2268';

        $this->upload->initialize($config);
        if (!$this->upload->do_upload("photoProfile")) {
            $error = array('error' => $this->upload->display_errors());
            echo $error["error"];
        }
        else{
        
            $username = $this->get_profile_infos->getUsername($this->input->cookie('LEAPSESSID'));
            $data = $this->upload->data();

            $user = $this->membership_model->getUserInfos($username);
            $org_picture = $this->s3->putObjectFile($data["file_path"] . $data["file_name"], "leap_s3","articles/" . $data["orig_name"], "public-read");

            $this->_createThumbnail($data["file_name"],$data["image_width"],$data["image_height"],300,"_big");
        
            echo $this->_createThumbnail($data["file_name"],$data["image_width"],$data["image_height"],50,"_thumb");
            
            $big_picture = $this->s3->putObjectFile($data["file_path"] . str_replace(".", "_big.", $data["file_name"]), "leap_s3", "articles/" . str_replace(".", "_big.", $data["orig_name"]), "public-read");
            $thmub_picture = $this->s3->putObjectFile($data["file_path"] . str_replace(".", "_thumb.", $data["file_name"]), "leap_s3", "articles/" . str_replace(".", "_thumb.", $data["orig_name"]), "public-read");

            $profile_pic = "https://s3.amazonaws.com/leap_s3/" . "articles/" . str_replace(".", "_big.", $data["orig_name"]);
            
            $this->settings->SureRemoveDir('./uploads', false);
            echo $profile_pic;
            
        }
    }
    function setCoverPostion(){
            $this->manage_login->updateData("profile_cover_pos",$this->input->post('position'),$this->input->cookie('LEAPSESSID'));
            
    }
    function shareVideo(){
        date_default_timezone_set('UTC');
        $video_id = $this->input->post("id");
        $title = $this->input->post("title");
        $desc = $this->input->post("desc");
        $thumb = $this->input->post("thumb");
        $hd = $this->input->post("hd");
        $identifier = $this->input->post("identifier");
        $uploaded_at =  date('F\, l j Y');
        $timestamp = time();
        $query = $this->share_media->addVideo($video_id,$title,$desc,$thumb,$identifier,$hd,$uploaded_at,$timestamp);
        echo $query;
    }
    function upload_image() {
        date_default_timezone_set('UTC');
        $config['upload_path'] = './uploads';
        $config['allowed_types'] = 'gif|jpg|png|JPG|jpeg';
        $config['max_size'] = '100000';
        $config['max_width'] = '2624';
        $config['max_height'] = '2268';

        $this->upload->initialize($config);
        if (!$this->upload->do_upload("feedimage")) {
            $error = array('error' => $this->upload->display_errors());
            echo $error["error"];
        }
        else{
        
            $username = $this->get_profile_infos->getUsername($this->input->cookie('LEAPSESSID'));
            $data = $this->upload->data();
            $image_id = $this->share_media->rand_string(12);

            $user = $this->membership_model->getUserInfos($username);
            $org_picture = $this->s3->putObjectFile($data["file_path"] . $data["file_name"], "leap_s3", $this->input->cookie('LEAPSESSID') . "/photo_feed/".$image_id."_". $data["orig_name"], "public-read");
            
            
            $profile_pic_original = "https://s3.amazonaws.com/leap_s3/" . $user[0]["user_id"] . "/photo_feed/".$image_id."_". $data["orig_name"];
            
            $this->thumbImage($data["file_name"],$data["image_width"],$data["image_height"]);
            $thmub_picture = $this->s3->putObjectFile($data["file_path"] . str_replace(".", "_thumb.", $data["file_name"]), "leap_s3", $this->input->cookie('LEAPSESSID') . "/photo_feed/".$image_id."_" . str_replace(".", "_thumb.", $data["orig_name"]), "public-read");
            $profile_pic_thumb = "https://s3.amazonaws.com/leap_s3/" . $user[0]["user_id"] . "/" . str_replace(".", "_thumb.", $data["orig_name"]);
            $thmub_source = "https://s3.amazonaws.com/leap_s3/" . $user[0]["user_id"] . "/photo_feed/".$image_id."_". str_replace(".", "_thumb.", $data["orig_name"]);
            
            $this->settings->SureRemoveDir('./uploads', false);
            
            $uploaded_at =  date('F\, l j\ - Y');
            $timestamp = time();
            $this->share_media->addImage($image_id,$data["orig_name"],$profile_pic_original,$thmub_source,(string)$data["image_width"],(string)$data["image_height"],$uploaded_at,$timestamp."");
            $var['image_source'] = $profile_pic_original;
            $var['image_id'] = $image_id;
            $var['content'] ='
                <input type="hidden" id="imgID" name="imgID"  value="" />
                        <span class="imagePlaceholder">
                            
                        </span>
                        <div class="imageInfos">
                            <label>Title</label>
                            <div class="shareTextarea" id="imageTitle">
                                
                                <div class="placeholder">Image Title ...</div>
                                <input type="text" id="imgTitle" name="imgTitle"/>
                            </div>
                                
                            <label>Description</label>
                            <div class="shareTextarea textareaWrapper" id="imageDesc">
                                
                                <div class="placeholder">Image Description ...</div>
                                <textarea type="text" id="imgDesc" name="imgDesc"></textarea>
                            </div>
                            <label>Photographer</label>
                            <div class="shareTextarea" id="imagePhotograph">
                                <div class="placeholder">Photographer</div>
                                <input type="text" id="photograph" name="photograph"/>
                            </div>
                     </div>
                ';
            echo json_encode($var);
        }
    }
    function thumbImage($fileName,$width,$height){
        $new_height = $height*(200/$width);
        $config['image_library'] = 'gd2';
        $config['source_image'] = $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $fileName;
        $config['new_image'] = $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $fileName;
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['thumb_marker'] = "_thumb";
        $config['width'] = 200;
        $config['height'] = $new_height;

        $this->load->library('image_lib', $config); 
        if (!$this->image_lib->resize()){
            return $this->image_lib->display_errors();
        }
        $this->image_lib->clear();
    }
    function shareImage (){
        $query = $this->share_media->editImageInfos($this->input->post('id'),$this->input->post('title'),$this->input->post('desc'),$this->input->post('photograph'));
        echo $query;
    }  
    function shareImage500px (){

        $image_id = $this->share_media->rand_string(9);
        $uploaded_at =  date('F\, l j\ - Y');
        $timestamp = time();
        
        $query = $this->share_media->add500pxImage($image_id,$this->input->post('source'),$this->input->post('thumb'),$this->input->post('title'),$this->input->post('desc'),$this->input->post('photograph'),$uploaded_at,$timestamp);
        echo $query;
    }
    function getvideosFromID(){
        $profile_id = $this->input->get("profile_id");
        $videos['videos'] = $this->share_media->getVideosFromID($profile_id);
        echo json_encode($videos);
    }
    function getphotosFromID(){
        $profile_id = $this->input->get("profile_id");
        $photos = $this->share_media->getPhotosFromID($profile_id);
        echo json_encode($photos);
    }
    function mood(){
        echo $this->get_profile_infos->editMood($this->input->post("moodMessage"));
    }
    function deletePost(){
        $id = $this->input->post("id");
        $type = $this->input->post("type");
        echo $this->share_media->deletePost($id,$type);
    }
}
